<template>
  <div class="login">
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit" class="my_form">
      <van-field
        v-model="loginname"
        name="用户名"
        label="手机号"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号不合法' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\S{6,}$/, message: '密码至少六位' }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" color="red"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { Toast } from 'vant'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      loginname: '17704051019',
      password: '123456'
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    onClickLeft () {
      this.$router.back()
    },
    //登录
    async onSubmit () {
      try {
        const res = await login({
          loginname: this.loginname,
          password: this.password
        })
        if (res.code === 200) {
          Toast({
            message: res.message,
            position: 'top'
          })
          // 保存到仓库中
          this.setToken(res.data.token)
          this.$router.push('/')
        } else {
          Toast.fail(res.message)
        }
        console.log('--res--', res)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// ::v-deep .van-icon {
//   color: #333;
// }
.my_form {
  margin-top: 5px;
}
</style>
